//
//  GKBookShelfController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2018/9/5.
//  Copyright © 2018 wangws1990. All rights reserved.
//
import UIKit

private var needLoad = true
class GKBookShelfController: BaseConnectionController {
    private lazy var listData: [GKBook] = {
        return []
    }()
    private lazy var navBarView: GKHomeNavBarView = {
        let navBarView = GKHomeNavBarView.instanceView()
        navBarView.chirdenBtn.addTarget(self, action: #selector(selectAction), for: .touchUpInside)
        return navBarView
    }()
    private lazy var recyleView : KLRecycleScrollView = {
        let recyleView = KLRecycleScrollView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH - 120, height: 30))
        recyleView.timerEnabled = true
        recyleView.pagingEnabled = false
        recyleView.scrollInterval = 4
        recyleView.direction = .left
        recyleView.delegate = self
        return recyleView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView.scrollsToTop = false
        self.fd_prefersNavigationBarHidden = true
        self.view.addSubview(self.navBarView)
        self.navBarView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(NAVI_BAR_HIGHT)
        }
        self.navBarView.tapView.addSubview(self.recyleView)
        self.recyleView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        self.collectionView.snp.remakeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.navBarView.snp.bottom)
        }
        self.recyleView.reloadData(appDatas.count)
        self.setupRefresh(scrollView: self.collectionView, options: .defaults)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navBarView.backgroundColor = moya.appColor
        self.collectionView.reloadData()
    }
    override func viewDidAppear(_ animated: Bool) {
        super .viewDidAppear(animated)
        self.refreshData(page: 1)
    }
    override func refreshData(page: Int) {
        GKShelfData.getBookModels { datas in
            if page == RefreshPageStart{
                self.listData.removeAll()
            }
            self.listData.append(contentsOf:datas)
            self.collectionView.reloadData()
            self.endRefresh(more: false, empty:"书架里面还没有任何小说!")
           // self.loadUpdateData()
        }
    }
    func loadUpdateData(){
        if needLoad{
            needLoad = false
            let group  = DispatchGroup();
            self.listData.forEach { book in
                if book.isSerial{
                    group.enter()
                    ApiMoya.request(target: .bookUpdate(book.bookId ?? "")) { json in
                        if let model = GKBook.deserialize(from: json.rawString()){
                            //服务端下发不是10位时间戳造成无法比对
                            if model.updated > book.updated && book.new == false{
                                book.updated = model.updated
                                book.new = true
                                book.lastChapter = model.lastChapter
                            }
                            GKShelfData.updateNew(bookId: book.bookId ?? "", newIcon: book.new ? 1 : 0, lastChap: book.lastChapter ?? "") { success in
                                group.leave()
                            }
                        }else{
                            group.leave()
                        }
                    } failure: { error in
                        group.leave()
                    }
                }
            }
            group.notify(queue: DispatchQueue.main) {
                self.refreshData(page: 1)
            }
        }
    }
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.listData.count
    }
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return listView ? 0 : 15
    }
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return GKBookCaseGridCell.inset
    }
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if listView {
            return CGSize(width: SCREEN_WIDTH, height: 140)
        }
        return GKBookCaseGridCell.cellSize
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if listView{
            let cell  = GKBookCaseCell.cellForCollectionView(collectionView: collectionView, indexPath: indexPath)
            cell.book = self.listData[indexPath.row];
            cell.delegate = self
            return cell
        }
        let cell = GKBookCaseGridCell.cellForCollectionView(collectionView: collectionView, indexPath: indexPath)
        cell.book = self.listData[indexPath.row];
        return cell
    }
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.listData[indexPath.row]
        GKJump.jumpToNovel(bookId: model.bookId)
    }

//    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        return self.listData.count
//    }
//    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return UITableView.automaticDimension
//    }
//    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = GKBookCaseCell.cellForTableView(tableView: tableView, indexPath: indexPath)
//        cell.book = self.listData[indexPath.row]
//        return cell
//    }
//    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        tableView.deselectRow(at: indexPath, animated: true)
//        let model = self.listData[indexPath.row]
//        GKJump.jumpToNovel(bookId: model.bookId)
//    }
//    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
//        return true
//    }
//    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
//        let model = self.listData[indexPath.row]
//        let context = UIContextualAction(style: .destructive, title: "删除") { row, index, finish in
//            self.deleteAction(model)
//        }
//        let title = model.topTime > 0 ? "取消置顶" : "置顶"
//        let top = UIContextualAction(style: .normal, title:title) { row, index, finish in
//            self.topAction(model)
//        }
//        let sw = UISwipeActionsConfiguration(actions: [context,top])
//        sw.performsFirstActionWithFullSwipe = false
//        return sw
//    }
    func deleteAction(_ model : GKBook){
        let name = model.title ?? ""
        ATAlertView.showAlertView(title: "确定将<\(name)>从书架中移除", message: nil, normals: ["取消"], hights: ["确定"]) { title, index in
            if index > 0{
                GKShelfData.deleteBookModel(bookId: model.bookId ?? "") { success in
                    self.listData.removeAll { item in
                        return item.bookId == model.bookId
                    }
                    self.collectionView.reloadData();
                }
            }else{
                self.collectionView.reloadData()
            }
        }
    }
    func topAction(_ model :GKBook){
        BaseShelfQueue().updateTop(bookId: model.bookId ?? "", cancle: model.topTime > 0 ? true : false) { sinish in
            self.refreshData(page: 1)
        }
    }
    @objc private func selectAction(){
        self.navBarView.chirdenBtn.isSelected = !self.navBarView.chirdenBtn.isSelected
        let select = self.navBarView.chirdenBtn.isSelected
        ApiClient.setGrid(select ? .grid : .list)
        self.collectionView.reloadData()
    }
    @objc private func addAction(){
        GKJump.jumpToSearch()
    }
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
}
extension GKBookShelfController :KLRecycleScrollViewDelegate{
    func recycleScrollView(_ recycleScrollView: KLRecycleScrollView!, viewForItemAt index: Int) -> UIView! {
        let label = UILabel();
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor.appx666666()
        label.text = appDatas[index]
        return label
    }
    func recycleScrollView(_ recycleScrollView: KLRecycleScrollView!, didSelect view: UIView!, forItemAt index: Int) {
        GKJump.jumpToSearch()
    }
}
extension GKBookShelfController :GKBookCaseCellDelegate{
    func moreTapAction(model: GKBook?) {
        guard let item = model else { return }
        let vc = GKActionSheetController(delegate: self, book: item)
        let rootVC = UIViewController.rootTopPresentedController()
        vc.hidesBottomBarWhenPushed = true
        rootVC.presentPanModal(vc)
    }
}
extension GKBookShelfController :GKActionSheetDelegate{
    func actionSheet(model :GKActionSheet,book :GKBook) {
        switch model.title {
        case .top:
            self.topAction(book)
            break
        case .bot:
            self.topAction(book)
            break
        case .deleBook:
            self.deleteAction(book)
            break
        case .mulu:
            GKJump.jumpToMulu(bookId: book.bookId ?? "")
            break
        default:
            break
        }
    }
}
